package com.njupt.Sort;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;


import javax.annotation.PostConstruct;
import java.util.Arrays;

@Data
@Component
public class MergeSort implements Sort {

    // 法2、依赖注入
    @Value("${nums}")
    private String numsConfig;
    private Integer[] nums;
    private Integer[] buffer;

    //在注入完成之后执行
    @PostConstruct
    public void init() {
        // 将逗号分隔的字符串转换为 Integer[] 数组
        this.nums = Arrays.stream(this.numsConfig.split(","))
                .map(Integer::parseInt)
                .toArray(Integer[]::new);

        if (nums != null) {
            buffer = new Integer[nums.length];
        }
    }


    public void sort(Integer[] nums, int left, int right) {
        if (left < right) {
            int mid = (left + right) / 2;
            sort(nums, left, mid);
            sort(nums, mid + 1, right);
            merge(nums, left, mid, right);
        }
    }

    private void merge(Integer[] nums, int left, int mid, int right) {

        int i, j, k;
        for (k = left; k <= right; k++) {
            buffer[k] = nums[k];
        }

        for (i = left, j = mid + 1, k = i
                     ; i <= mid && j <= right; k++) {
            if (buffer[i] <= buffer[j]) {
                nums[k] = buffer[i++];
            } else {
                nums[k] = buffer[j++];
            }
        }
        while (i <= mid) nums[k++] = buffer[i++];
        while (j <= right) nums[k++] = buffer[j++];

    }

    public void hello(String name,String toName){
        System.out.println(name + " 对你说：" + toName);
    }

//    public static void main(String[] args) {
////        int[] arrays = {1,7,5,2,4,3,10,20,19,18};
////        MergeSort mergeSort = new MergeSort();
//
//        ClassPathXmlApplicationContext context
//                = new ClassPathXmlApplicationContext("applicationContext.xml");
//        MergeSort mergeSort = (MergeSort) context.getBean(MergeSort.class);
//        mergeSort.sort(mergeSort.nums, 0, mergeSort.nums.length - 1);
//        System.out.println(Arrays.toString(mergeSort.nums));
//    }
}
